package com.smartcanteen.user.controller.user;


import com.smartcanteen.constant.JwtClaimsConstant;
import com.smartcanteen.properties.JwtProperties;
import com.smartcanteen.user.domain.dto.UserAccountLoginDTO;
import com.smartcanteen.user.domain.dto.UserDTO;
import com.smartcanteen.user.domain.dto.UserLoginDTO;
import com.smartcanteen.user.domain.entity.User;
import com.smartcanteen.user.domain.vo.MerchantVO;
import com.smartcanteen.user.domain.vo.UserLoginVO;
import com.smartcanteen.user.mapper.UserMapper;
import com.smartcanteen.user.service.UserService;
import com.smartcanteen.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.smartcanteen.result.Result;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户传过来的登录信息：{}", userLoginDTO);
        User user = userService.wxLogin(userLoginDTO);

        // 上面的没抛异常，正常来到这里，说明登录成功
        // claims就是用户数据payload部分
        Map<String, Object> claims = new HashMap<>(); // jsonwebtoken包底层就是Map<String, Object>格式，不能修改！
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        // 需要加个token给他，再返回响应
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
    @PostMapping("/loginByAccount")
    public Result<UserLoginVO> loginByAccount(@RequestBody UserAccountLoginDTO loginDTO) {
        log.info("账号密码登录信息：{}", loginDTO);

        // 调用服务层校验账号密码
        User user = null;
        try {
            user = userService.validateAccountPassword(loginDTO.getAccount(), loginDTO.getPassword());

            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getId());
            String token = JwtUtil.createJWT("Y7h8Gv3qPzX9K2mNpLrT0sA",
                    3600000,
                    claims);

            // 构建返回对象
            UserLoginVO vo = UserLoginVO.builder()
                    .id(user.getId())
                    .account(user.getAccount()) // 增加账号字段
                    .token(token)
                    .build();
            return Result.success(vo);
        } catch (Exception e) {
            // 抛出异常，前端会捕获，并提示账号或密码错误
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据id查询用户
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Integer id){
        log.info("用户id:{}", id);
        User user = userService.getUser(id);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param userDTO
     * @return
     */
    @PutMapping
    public Result update(@RequestBody UserDTO userDTO){
        log.info("新的用户信息：{}", userDTO);
        userService.update(userDTO);
        return Result.success();
    }

    /**
     * 根据id查询用户
     * @return
     */
    @GetMapping("/api/getUser")
    public User getUserForApi(Integer id){
        log.info("用户id:{}", id);
        return userService.getUser(id);
    }
    /**
     * 根据merchantId查询商家
     * @return
     */
    @GetMapping("/getMerchant")
    public Result<MerchantVO> getMerchant(@RequestParam Integer merchantId){
        log.info("商家id:{}", merchantId);
        MerchantVO merchant = userMapper.getMerchant(merchantId);
        log.info("商家信息:{}", merchant);
        return Result.success(merchant);
    }
}
